#include "../engine/core.h"
#include "DBMsgHandler.h"
#include "../engine/ComputureMgr.h"
#include "../engine/Protocal/Common.pb.h"
#include "../engine/AsioTcpLink.h"
#include "../engine/AsioTcpLinkClient.h"
#include "../engine/GlobalConfig.h"
#include "../engine/ServerCore.h"
#include "../engine/Misc.h"
#include "../engine/LogMgr.h"
#include "../engine/UserMgr.h"
#include "../engine/DbExecute.h"
#include "../engine/xTime.h"

IMP_SINGLETON_CLASS(CDBMsgHandler)

CDBMsgHandler::CDBMsgHandler()
{
	Reg();
}

CDBMsgHandler::~CDBMsgHandler()
{
	UnReg();
}

void CDBMsgHandler::UnReg()
{
	CPacketProcesser* processer = CPacketProcesser::getInstance();
	if (processer)
	{
		processer->UnReg(MYTH::CMD_User_Login);
	}
}

void CDBMsgHandler::Reg()
{
	CPacketProcesser* processer = CPacketProcesser::getInstance();
	if (processer)
	{
		processer->RegCB(MYTH::CMD_User_Login, boost::BOOST_BIND(&CDBMsgHandler::OnUserLogin, this, _1));
//		processer->RegCB(MYTH::CMD_User_Login_r, boost::BOOST_BIND(&CDBMsgHandler::OnUserLogin_r, this, _1));
	}
}

void CDBMsgHandler::OnUserLogin(xMSG& msg)
{
	net_link_ptr link_ptr = boost::dynamic_pointer_cast<CAsioTcpLink>(xNetObjBase::getNetObj(msg.call_guid));
	if (link_ptr.get())
	{
		MYTH::AccountLogin UserLogin;
		if (UserLogin.ParseFromArray(msg.getParameterData(), msg.getParameterSize()))
		{
			CUserMgr* pUserMgr = CUserMgr::getInstance();
			CServerCore* pServerCore = CServerCore::getInstance();
			CComputureMgr* pSrvMgr = CComputureMgr::getInstance();
			
			MYTH::AccountLogin_R r;
			CSrvComputure* gate = NULL;
			CSrvComputure* game = NULL;
			r.set_err_code(MYTH::Error_Success);
			CUser* pUser = pUserMgr->getUser(UserLogin.account_id());
			if (pUser)
			{
				if (!(UserLogin.account_pwd() == UserLogin.account_pwd()))
				{
					r.set_err_code(MYTH::Error_PassWord);
				}
				else
				{
					pUser->LoadRoleList();
					*r.mutable_role_list() = *pUser->user.mutable_role_list();
					gate = pSrvMgr->getLightServer(ENetDef::NET_GATE);
					if (!gate)
					{
						GAMELOGER->error("OnUserLogin no gate server!");
						return;
					}
					game = pSrvMgr->getLightServer(ENetDef::NET_GAME_WORLD);
					if (!game)
					{
						GAMELOGER->error("OnUserLogin no game server!");
						return;
					}
					r.set_gate_ip_port(gate->getm_strIPPort());
					r.set_game_ip_port(game->getm_strIPPort());
					r.set_key(xTime::getTimeStr());
				}
			}
			else 
			{
				r.set_err_code(MYTH::Error_NoUser);
			}
			
			xMSG rl(MYTH::CMD_User_Reg_r, &r);
			link_ptr->prepWrite(rl.msg_ptr, rl.dwLen);
			if (gate)
			{
				gate->SendMsg2Server(msg);
			}
			if (game)
			{
				game->SendMsg2Server(msg);
			}
		}
	}
}